package com.hzt.agprosaleplatform.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzt.agprosaleplatform.entity.Article;
import com.hzt.agprosaleplatform.entity.Expert;
import com.hzt.agprosaleplatform.entity.ExpertQuestion;
import com.hzt.agprosaleplatform.entity.ShortQuestionDTO;
import com.hzt.agprosaleplatform.mapper.ArticleMapper;
import com.hzt.agprosaleplatform.mapper.ExpertMapper;
import com.hzt.agprosaleplatform.service.ExpertService;
import com.hzt.agprosaleplatform.utils.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.sql.Timestamp;
import java.util.*;

/**
 * 农技学堂服务
 */
@Service
public class ExpertServiceImpl implements ExpertService {

    @Autowired
    ExpertMapper expertMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    private OssUtil ossUtil;

    @Value("${oss.bucketUrl}")
    private String OSS_BUCKET_URL;


    //首页展示三个专家信息
    @Override
    public List<Expert> RecommendedExperts() {
        return expertMapper.selectRecommendedExperts();
    }

    //专家认证
    @Override
    public Expert BeExpert(Expert expert) {
        int result = expertMapper.insert(expert);
        if(result > 0){
            return expert;
        }else {
            return null;
        }
    }

    //发布科普文章(类似发布商品)
    @Override
    public Article postArticle(Article article, List<MultipartFile> articleImages) {
        try {
            // 初始化文章基本信息
            article.setView_count(0);
            article.setLike_count(0);

            Timestamp now = new Timestamp(System.currentTimeMillis());
            article.setCreated_date(now);
            article.setUpdated_date(now);
            
            // 处理封面图片 第0张存为封面照片
            if (!articleImages.isEmpty()) {
                MultipartFile coverImage = articleImages.get(0);
                String coverImageUrl = ossUtil.uploadArticleImg(coverImage, "coverImg");
                article.setCover_image(coverImageUrl);
            }
            
            // 插入文章基本信息
            int result = articleMapper.insert(article);
            if (result <= 0) {
                throw new RuntimeException("文章内容插入失败");
            }

            // 处理文章内容图片
            if (articleImages.size() > 1) {
                for (int i = 1; i < articleImages.size(); i++) {
                    String contentImageUrl = ossUtil.uploadArticleImg(articleImages.get(i), "contentImg");
                    expertMapper.insertArticleImage(article.getArticle_id(), contentImageUrl);
                }
            }
            return article;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发布文章失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getArticleWithImages(Integer articleId) {
        // 获取文章基本信息
        Article article = articleMapper.selectById(articleId);
        if (article == null) {
            throw new RuntimeException("文章不存在");
        }

        // 获取文章相关的图片
        List<String> images = expertMapper.getArticleImages(articleId);

        // 组装返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("content", article.getContent());
        response.put("images", images);
        response.put("title", article.getTitle());
        response.put("coverImage", article.getCover_image());
        response.put("createdDate", article.getCreated_date());

        return response;
    }

    @Override
    public List<Article> getArticleCard() {
        return expertMapper.getArticleCard();
    }

    @Override
    public ExpertQuestion addNewQuestion(ExpertQuestion expertQuestion) {
        expertQuestion.setStatus(0);
        expertQuestion.setAdoptNumbers(0);
        int result = expertMapper.insertQuestion(expertQuestion);

        if(result > 0){
            return expertQuestion;
        }else {
            return null;
        }
    }

    //获取问题
    @Override
    public ExpertQuestion selectQuestionByQid(int qid) {
        return expertMapper.selectQuestionByQid(qid);
    }

    @Override
    public ExpertQuestion answerQuestion(Integer qid,String answer) {
        //更新回答
        int result = expertMapper.updateAnswer(qid,answer);
        if(result > 0){
            return expertMapper.selectQuestionByQid(qid);
        }
        return null;
    }

    @Override
    public String moreAnswer(String uid,Integer qid, String answer) {
        try {

            int result = expertMapper.moreAnswerToQ(uid,qid,answer);

            if(result > 0) {
                return "回答成功";
            }
            return "回答失败";
        } catch (Exception e) {
            e.printStackTrace();
            return "系统错误";
        }
    }

    @Override
    public List<ExpertQuestion> getMoreAnswer(Integer qid) {
        try {
            return expertMapper.getMoreAnswerByQid(qid);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public IPage<ExpertQuestion> ListAllQuestion(int pageNum, int pageSize) {
        Page<ExpertQuestion> page = new Page<>(pageNum, pageSize);
        return expertMapper.ListAllQuestion(page);
    }

    @Override
    public Expert selectExpertById(String eid) {
        return expertMapper.selectExpertById(eid);
    }

    @Override
    public List<ShortQuestionDTO> shortQuestionList(String eid) {
        return expertMapper.selectShortQuestionsByEid(eid);
    }

}
